import { PlusOutlined, EditOutlined, DiffOutlined, DeleteOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { PageContainer, ProTable } from '@ant-design/pro-components';
import { Button, Divider, Popconfirm, message } from 'antd';
import { useRef,useState } from 'react';

import { queryTreeList, addUpdate, remove, StudyCatalogParams, StudyCatalogItem } from '@/services/study/catalog';
import StudyCatalogForm from './studyCatalogForm';

export default () => {
    const [open, setOpen] = useState<boolean>(false);
    const [studyCatalogItem, setStudyCatalogForm] = useState<Partial<StudyCatalogItem> | undefined>();
    const actionRef = useRef<ActionType>();

    /**
     * 添加编辑目录
     * @param fields
    */
    const handleSubmit = async (fields: StudyCatalogItem) => {
        setOpen(false);
        const msg = fields.id ? '编辑' : '添加';
        message.loading('正在' + msg + '目录');
        const res = await addUpdate({ ...fields });

        if (res.success) {
            message.success(msg + '目录成功');
            if (actionRef.current) {
                actionRef.current.reload();
            }
        } else {
            message.error(res.msg);
        }
    };

    /**
     * 删除目录
     * @param item
    */
    const handleRemove = async (item: StudyCatalogItem) => {
        if(item.children){
            message.error('请删除 ' + item.name + ' 下的子目录');
        }else{
            message.loading('正在删除 ' + item.name + ' 目录');
            const res = await remove(item.id);
            if (res.success) {
              message.success(item.name + '目录删除成功');
              if (actionRef.current) {
                actionRef.current.reload();
              }
            } else {
              message.error(res.msg);
            }
        }
    };

    const showAddModal = () => {
        setOpen(true);
        setStudyCatalogForm({ optType: 'add' });
    };

    const showEditModal = (item: StudyCatalogItem) => {
        setOpen(true);
        setStudyCatalogForm(item);
    };

    const columns: ProColumns<StudyCatalogItem>[] = [
        {
            dataIndex: 'id',
            valueType: 'indexBorder',
            width: 90,
        },
       
        {
          title: '名称',
          dataIndex: 'name',
          copyable: true,
        },
        {
            title: '排序',
            dataIndex: 'sortNum',
            width: 60
        },
        {
          title: '操作',
          valueType: 'option',
          width: 120,
          render: (_, record)  => [
            <a
                key="edit"
                onClick={() => {
                    showEditModal({ ...record, optType: 'edit' })
                }}
                title="编辑目录"
            >
              <EditOutlined />
            </a>,
            <Divider type="vertical" />,
            <a
                key="addSub"
                onClick={() => {
                    showEditModal({
                        parentid: record.id,
                        optType: 'addSub' 
                    })
                }}
                title="添加子目录"
            >
                <DiffOutlined />
            </a>,
            <Divider type="vertical" />,
            <Popconfirm title="是否要删除此目录？" onConfirm={() => handleRemove(record)}>
                <a key="delete" title="删除目录">
                    <DeleteOutlined />
                </a>
            </Popconfirm>
          ],
        },
    ];

    return (
        <PageContainer title={false}>
            <ProTable<StudyCatalogItem>
                rowKey="id"
                actionRef={actionRef}
                columns={columns}
                request={(params) => {
                    params.keyword
                    return queryTreeList(params as StudyCatalogParams);
                }}
                search={false}
                toolBarRender={() => [
                    <Button
                        key="button"
                        icon={<PlusOutlined />}
                        onClick={() => {
                            showAddModal();
                        }}
                        title="添加目录"
                        type="primary">
                    </Button>
                ]}
                pagination={false}     
            />
            <StudyCatalogForm
                studyCatalogItem={studyCatalogItem}
                open={open}
                onCancel={() => setOpen(false)}
                onSubmit={handleSubmit}
            />
        </PageContainer>
    );
};